using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ShopForWeb.UI.Models;

namespace ShopForWeb.UI.Utils.Filters
{
    public class AdminAuthroizeAttribute:Attribute,IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
          var session=context.HttpContext.Session;
           string?jsonString;
           jsonString=session.GetString("key-admin");
           if(string.IsNullOrEmpty(jsonString))
           {
              HandleUnAuthorize(context);
           }
        }
        private void HandleUnAuthorize(AuthorizationFilterContext context)
        {
            var request=context.HttpContext.Request;
            if(request.Headers["X-Requested-With"]=="XMLHttpRequest")
            {
              //context.Result=new StatusCodeResult(403);
              context.Result=new JsonResult(new ResponseViewModel()
              {
                Code=403,
                Message="无此权限，请先登录"
              });
            }
            else
            context.Result=new RedirectToActionResult("Index","Identity",new{Area="admin"});
        }



    }
}